package cn.buk.api.szkj.service;

import cn.buk.api.szkj.dto.eterm.request.UserInfo;
import cn.buk.common.util.EncryptUtil;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import static cn.buk.common.util.EncryptUtil.Base64Encoding;


public abstract class AbstractServiceImpl {

  private static final Logger logger = LogManager.getLogger(AbstractServiceImpl.class);

  /**
   * 快捷游平台用户名
   */
  protected final String username;
  protected final String apiUrl;
  protected boolean debugMode;

  protected AbstractServiceImpl(String username, String apiUrl) {
    this.username = username;
    this.apiUrl = apiUrl;
  }

  protected List<NameValuePair> prepareParams(final String functionName,
                                              final String username,
                                              final String requestStr) {
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("fun_name", functionName));
    params.add(new BasicNameValuePair("user_name", username));

    String base64Request = null;
    try {
      base64Request = Base64Encoding(requestStr);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    params.add(new BasicNameValuePair("request", base64Request));

    if (this.debugMode) {
      logger.info("request: {}", requestStr);
      for (NameValuePair p : params) {
        logger.info("{}: {}", p.getName(), p.getValue());
      }
      logger.info("url: {}", this.apiUrl);
    }

    return params;
  }

  protected UserInfo prepareUserInfo(String etermUsername, String etermPassword, int queryId) {
    UserInfo userInfo = new UserInfo();

    userInfo.setEtermUser(etermUsername);
    try {
      userInfo.setEtermPwd(EncryptUtil.MD5Encoding(etermPassword));
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    userInfo.setQueryId(queryId);

    return userInfo;
  }

  public void setDebugMode(boolean debugMode) {
    this.debugMode = debugMode;
  }
}
